var express = require('express');
var router = express.Router();
const Core = require('@alicloud/pop-core');
const OSS = require('ali-oss');
var path = require('path')
var http = require('http')
var fs = require('fs')

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/getstarphoto', (req, res, next) => {
  const { starUrl } = req.body

  var client = new Core({
    accessKeyId: 'LTAI4Fz46pywB92UJjYNhgxh',
    accessKeySecret: '9s9M4MvIW4yyX7mwyFcHKohAmJdQS2',
    endpoint: 'https://imageseg.cn-shanghai.aliyuncs.com',
    apiVersion: '2019-12-30'
  });

  var params = {
    "RegionId": "cn-shanghai",
    ImageURL: starUrl
  }

  var requestOption = {
    method: 'GET'
  };

  client.request('SegmentBody', params, requestOption).then(async (result) => {
    let url = result.Data.ImageURL
    // 将该图片下载到oss域名下
    netUrlToOss(url, (ossData, img_filename)=>{
      console.log(ossData.url, 'ossData.url');

      console.log('tmp/' + img_filename);
      deleteDir('tmp/' + img_filename)

      res.send({ code: 1, url: ossData.url, msg: '获取成功' })
    })
  }, (ex) => {
    console.log(ex);
  })
})


var multer = require('multer')
var upload = multer({ dest: 'tmp/' })
router.post('/upload', upload.single('file'), async (req, res) => {
  let path = req.file.path
  let originalname = req.file.originalname
  // 获得到上传的img_url

  let result = await putStream(path, originalname)

  // tmp\abe0540355da563663d3f1120991141e
  deleteDir(path)

  res.send({ code: 1, msg: '获取成功', data: result })
})
async function deleteDir(path){
  var isDelete = false
  const res = await fs.unlink(__dirname + '/../' + path, (err) => {
    if (err) throw err;
    isDelete = true
    console.log('删除成功');
  });
  return res
}

async function putStream(path, originalname) {
  console.log(originalname, 'originalname');
  const client = new OSS({
    accessKeyId: 'LTAI4G8uNgE8wHmh98en37hg',
    accessKeySecret: 'kjBv7T3tsZNdeMvV9tV7RBNA00gatF',
    bucket: 'glack',
    region: 'oss-cn-shanghai',
  });

  try {
    let fs = require('fs');
    let stream = fs.createReadStream(path);
    // console.log(stream, 'stream');
    // console.log(originalname, 'originalname');
    var result = await client.putStream(originalname, stream);
  } catch (e) {
    console.log(e);
  }
  return result
}
async function netUrlToOss(netUrl, callBack) {
  var ossData
  var img_filename = Date.parse(new Date()) + '.jpg';

  http.get(netUrl, function (res) {
    var imgData = "";
    res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
    res.on("data", function (chunk) {
      imgData += chunk;
    });
    res.on("end", function () {
      fs.writeFile(path.join(__dirname + '/../tmp/' + img_filename), imgData, "binary", async function (err) {
        if (err) {
          console.log(err, 'err');
          console.log("保存失败");
        }
        
        ossData = await putStream('tmp/' + img_filename, img_filename)
        callBack(ossData, img_filename)
        
      });
    });
    res.on("error", function (err) {
      console.log("请求失败");
    });
  });

}

module.exports = router;